package com.gravata.enigma.fragments;

import java.sql.SQLException;
import java.util.List;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.gravata.enigma.Confirm;
import com.gravata.enigma.R;
import com.gravata.enigma.ReloadDataListener;
import com.gravata.enigma.activities.FavoritoActivity;
import com.gravata.enigma.activities.TelaInicial;
import com.gravata.enigma.dragdrop.listview.DragListener;
import com.gravata.enigma.dragdrop.listview.DragNDropAdapter;
import com.gravata.enigma.dragdrop.listview.DragNDropListView;
import com.gravata.enigma.dragdrop.listview.DropListener;
import com.gravata.enigma.dragdrop.listview.RemoveListener;
import com.gravata.enigma.model.Bouquet;
import com.gravata.enigma.model.BouquetService;
import com.gravata.enigma.quickaction.QuickActionBar;
import com.gravata.enigma.quickaction.QuickActionIcons;

public class BouquetsFragment extends Fragment implements ReloadDataListener {

	/**group items*/
    private DragNDropListView eList;
    private DragNDropAdapter dragAdapter;
    private QuickActionBar qab;
    private boolean loaded=false;


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_bouquet, container, false);

        eList = (DragNDropListView) rootView.findViewById(R.id.list_view_customizer);
        eList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        dragAdapter=new DragNDropAdapter(this.getActivity(), new int[]{R.layout.row_item}, new int[]{R.id.txt__customizer_item},  TelaInicial.bouquets);
        eList.setAdapter(dragAdapter);
        eList.setLongClickable(true);
        Button btnAdd=(Button) rootView.findViewById(R.id.favorito_add);

        if (eList instanceof DragNDropListView) {
        	((DragNDropListView) eList).setDropListener(mDropListener);
        	((DragNDropListView) eList).setRemoveListener(mRemoveListener);
        	((DragNDropListView) eList).setDragListener(mDragListener);
        }

        eList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            int previousGroup = -1;

            @Override
            public void onGroupExpand(int groupPosition) {
                if(groupPosition != previousGroup)
                    eList.collapseGroup(previousGroup);
                previousGroup = groupPosition;
            }
        });


        btnAdd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent=new Intent(getActivity(),FavoritoActivity.class);
				startActivityForResult(intent, TelaInicial.BOUQUET_INSERT);
			}
		});


        final QuickActionIcons edit = new QuickActionIcons();

		edit.setTitle(getString(R.string.editar));
		edit.setIcon(getResources().getDrawable(android.R.drawable.ic_menu_edit));
		edit.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent=new Intent(getActivity(),FavoritoActivity.class);
				int request=-1;

				if(qab.getChildPosition()==-1){
					intent.putExtra("bouquet", dragAdapter.getGroup(qab.getGroupPosition()) );
					request=TelaInicial.BOUQUET_EDIT;
					collapseAll();
				}
				qab.hide();

				startActivityForResult(intent, request);
			}

		});


		 final QuickActionIcons excluir = new QuickActionIcons();

		 excluir.setTitle(getString(R.string.excluir));
		 excluir.setIcon(getResources().getDrawable(android.R.drawable.ic_menu_delete));
		 excluir.setOnClickListener(new OnClickListener() {

			 	public void onClick(View v) {

					Confirm confirm=new Confirm(getActivity(), getString(R.string.confirmar_exclusao), getString(R.string.confirmar_exclusao_bouquet), new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

							String name="";
							if(qab.getChildPosition()==-1){
								Bouquet bouquet= dragAdapter.getGroup(qab.getGroupPosition());
								name=bouquet.getName();

								try {
									TelaInicial.repositorioBouquets.excluir(bouquet);
									TelaInicial.reloadBouquetData();
									dragAdapter.setData(TelaInicial.bouquets);
									collapseAll();
								} catch (SQLException e) {
									e.printStackTrace();
								}

							}else{
								BouquetService bouquetService=dragAdapter.getChild(qab.getGroupPosition(), qab.getChildPosition());
								name= bouquetService.getService().getName();
								try {
									TelaInicial.repositorioBouquetService.excluir(bouquetService);
									TelaInicial.reloadBouquetData();
								} catch (SQLException e) {
								}
							}

							qab.hide();

							Toast.makeText(getActivity(),
									name+" "+getString(R.string.excluido_sucesso), Toast.LENGTH_SHORT).show();
							dragAdapter.notifyDataSetChanged();

						}
					} ,new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							qab.hide();
						}
					} );
					confirm.show();
				}

			});

		eList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

				int itemtype= ExpandableListView.getPackedPositionType(id);
				int childPosition=-1;
				int groupPosition;
				if (itemtype == ExpandableListView.PACKED_POSITION_TYPE_CHILD){
					childPosition =ExpandableListView.getPackedPositionChild(id);
					groupPosition=ExpandableListView.getPackedPositionGroup(id);
				}else{
					groupPosition=ExpandableListView.getPackedPositionGroup(id);
				}


				qab = new QuickActionBar(view);

				qab.setChildPosition(childPosition);
				qab.setGroupPosition(groupPosition);

				Bouquet bouquet=null;
				if(itemtype==ExpandableListView.PACKED_POSITION_TYPE_GROUP){
					bouquet= dragAdapter.getGroup(groupPosition);
					if(!bouquet.isFavorites())
						qab.addItem(edit);
				}
				if(itemtype==ExpandableListView.PACKED_POSITION_TYPE_CHILD){
					qab.addItem(excluir);
				}else{
					if(!bouquet.isFavorites())
						qab.addItem(excluir);
				}


			    qab.setAnimationStyle(QuickActionBar.GROW_FROM_LEFT);
			    qab.show();

				return true;
			}
		});

		return rootView;
	}

	private void collapseAll(){
		int count=dragAdapter.getGroupCount();

		for(int a=0;a<count;a++)
			eList.collapseGroup(a);
	}

	@Override
	public void onResume() {
		super.onResume();
		dragAdapter.setData(TelaInicial.bouquets);
	}

	/**implementing the drop listener*/
    private DropListener mDropListener =
    		new DropListener() {
            public void onDrop(int[] from, int[] to) {
            	ExpandableListAdapter adapter = eList.getExpandableListAdapter();
            	if (adapter instanceof DragNDropAdapter) {
            		((DragNDropAdapter)adapter).onDrop(from, to); // send the event to adapter and manipulate items in the arraylists
            		eList.invalidateViews(); //redraw the list view
            	}
            }
        };
        /**remove item from the list*/
        private RemoveListener mRemoveListener =
            new RemoveListener() {
            public void onRemove(int which[]) {
            	ExpandableListAdapter adapter = eList.getExpandableListAdapter();
            	if (adapter instanceof DragNDropAdapter) {
            		((DragNDropAdapter)adapter).onRemove(which);
            		eList.invalidateViews();
            	}
            }
        };

        private DragListener mDragListener =
        	new DragListener() {

        	int backgroundColor = 0xe0103010; // different color to identify
        	int defaultBackgroundColor;

    			public void onDrag(int x, int y, ExpandableListView listView) {
    				// TODO Auto-generated method stub
    			}

    			public void onStartDrag(View itemView) {
    				itemView.setVisibility(View.INVISIBLE); // make the item invisible as we have picked it
    				defaultBackgroundColor = itemView.getDrawingCacheBackgroundColor(); // fill the empty space with default color
    				itemView.setBackgroundColor(backgroundColor);
    				ImageView iv = (ImageView)itemView.findViewById(R.id.move_icon_customizer_item);
    				if (iv != null) iv.setVisibility(View.INVISIBLE);
    			}

    			public void onStopDrag(View itemView) {
    				itemView.setVisibility(View.VISIBLE);
    				itemView.setBackgroundColor(defaultBackgroundColor);
    				ImageView iv = (ImageView)itemView.findViewById(R.id.move_icon_customizer_item);
    				if (iv != null) iv.setVisibility(View.VISIBLE);
    			}

        };


		public void onActivityResult(int requestCode, int resultCode, Intent data) {
			if(resultCode==1){
				TelaInicial.reloadBouquetData();
				dragAdapter.notifyDataSetChanged();
			}
			super.onActivityResult(requestCode, resultCode, data);
		}

		@Override
		public void onReloadData() {
			dragAdapter.setData(TelaInicial.bouquets);
		}

		@Override
		public void onFealoadData(List<?> list) {
			// TODO Auto-generated method stub

		};

}
